package teachnotes.guides.server;

import teachnotes.guides.compute.Compute;
import teachnotes.guides.engine.ComputeEngine;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Logger;

/**
 * @author xiaoming
 * @date 2020-07-03 6:35
 */
public class Server {

    private static Logger log = Logger.getLogger(Server.class.getSimpleName());

    public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            // 用于检查应用程序是否能够访问一些有限的资源
            // 创建安全管理器: 如果没有 , RMI 则 不会作为远程方法调用
            System.setSecurityManager(new SecurityManager());
        }

        try {
            // 为对象创建名称
            String name = "Compute";
            // 使远程对象对客户端可用  , 创建实例
            Compute engine = new ComputeEngine();
            //把接口对象暴露到网络
            Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
            // 打开端口
//            LocateRegistry.createRegistry(1199);
            // 将名称添加到运行在服务器的 RMI 注册表
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);

            log.info("ComputeEngine bound");

        } catch (Exception e) {
            // 如何远程调用将导致抛出 RemoteException
//                throw new RemoteException()
            log.warning(e.getMessage());
            e.printStackTrace();
        }
    }

}
